<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 检查登录状态
check_login();

$db = db_connect();

// 获取搜索参数
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$date = isset($_GET['date']) ? trim($_GET['date']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';

// 分页参数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// 构建查询条件
$where = "1=1";
$params = [];

if ($search) {
    $where .= " AND c.name LIKE :search";
    $params[':search'] = "%{$search}%";
}

if ($date) {
    $where .= " AND cs.date = :date";
    $params[':date'] = $date;
}

if ($status !== '') {
    $where .= " AND cs.is_available = :status";
    $params[':status'] = $status;
}

// 获取总记录数
$count_sql = "SELECT COUNT(*) 
              FROM coach_schedules cs 
              LEFT JOIN coaches c ON cs.coach_id = c.id 
              WHERE {$where}";
$count_stmt = $db->prepare($count_sql);
foreach ($params as $key => $value) {
    $count_stmt->bindValue($key, $value);
}
$count_stmt->execute();
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $per_page);

// 获取教练的排班信息
$schedule_sql = "SELECT cs.*, c.name as coach_name 
                 FROM coach_schedules cs 
                 LEFT JOIN coaches c ON cs.coach_id = c.id 
                 WHERE {$where}
                 ORDER BY cs.date DESC, cs.time_slot
                 LIMIT {$offset}, {$per_page}";
$schedule_stmt = $db->prepare($schedule_sql);
foreach ($params as $key => $value) {
    $schedule_stmt->bindValue($key, $value);
}
$schedule_stmt->execute();
$schedules = $schedule_stmt->fetchAll(PDO::FETCH_ASSOC);

// 处理状态切换和删除操作
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    
    if ($_GET['action'] === 'toggle') {
        $sql = "UPDATE coach_schedules SET is_available = NOT is_available WHERE id = :id";
        $stmt = $db->prepare($sql);
        $stmt->execute([':id' => $id]);
    } elseif ($_GET['action'] === 'delete') {
        $sql = "DELETE FROM coach_schedules WHERE id = :id";
        $stmt = $db->prepare($sql);
        $stmt->execute([':id' => $id]);
    }
    
    header('Location: private_courses.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>教练排班管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body>
    <div class="wrapper">
        <?php include 'includes/sidebar.php'; ?>
        
        <div class="main-content">
            <header class="top-header">
                <div class="header-left">
                    <h2>教练排班管理</h2>
                </div>
                <div class="header-right">
                    <a href="schedule_add.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 添加排班
                    </a>
                </div>
            </header>

            <div class="content">
                <!-- 搜索和筛选 -->
                <div class="filter-bar">
                    <form action="" method="GET" id="searchForm" class="search-bar">
                        <input type="text" name="search" placeholder="搜索教练姓名..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                        <input type="date" name="date" value="<?php echo $date; ?>" 
                               onchange="document.getElementById('searchForm').submit()">
                        <select name="status" onchange="document.getElementById('searchForm').submit()">
                            <option value="">全部状态</option>
                            <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>可用</option>
                            <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>不可用</option>
                        </select>
                        <button type="submit"><i class="fas fa-search"></i></button>
                    </form>
                </div>

                <!-- 数据表格 -->
                <div class="data-table">
                    <table>
                        <thead>
                            <tr>
                                <th>教练</th>
                                <th>日期</th>
                                <th>时间段</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($schedules)): ?>
                            <tr>
                                <td colspan="5" class="text-center">暂无数据</td>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($schedules as $schedule): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($schedule['coach_name']); ?></td>
                                    <td><?php echo date('Y-m-d', strtotime($schedule['date'])); ?></td>
                                    <td><?php echo htmlspecialchars($schedule['time_slot']); ?></td>
                                    <td>
                                        <span class="badge <?php echo $schedule['is_available'] ? 'badge-success' : 'badge-danger'; ?>">
                                            <?php echo $schedule['is_available'] ? '可用' : '不可用'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <a href="javascript:void(0)" 
                                           onclick="toggleStatus(<?php echo $schedule['id']; ?>)"
                                           class="btn-icon" title="切换状态">
                                            <i class="fas fa-sync-alt"></i>
                                        </a>
                                        <a href="javascript:void(0)" 
                                           onclick="deleteSchedule(<?php echo $schedule['id']; ?>)"
                                           class="btn-icon text-danger" title="删除">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <?php if ($total_pages > 1): ?>
                <div class="pagination">
                    <?php 
                    // 生成分页链接
                    $params = array_merge($_GET, ['page' => '']);
                    echo generate_pagination($page, $total_pages, $params);
                    ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <style>
    .filter-bar {
        background: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        margin-bottom: 20px;
    }

    .search-bar {
        display: flex;
        gap: 15px;
        align-items: center;
        flex-wrap: wrap;
    }

    .search-bar input[type="text"],
    .search-bar input[type="date"],
    .search-bar select {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: all 0.3s;
    }

    .search-bar input[type="text"]:focus,
    .search-bar input[type="date"]:focus,
    .search-bar select:focus {
        border-color: #3498db;
        box-shadow: 0 0 0 2px rgba(52,152,219,0.2);
    }

    .search-bar button {
        padding: 8px 15px;
        background: #3498db;
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: background 0.3s;
    }

    .search-bar button:hover {
        background: #2980b9;
    }

    .header-right {
        margin-left: auto;
    }
    
    .data-table {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        overflow: hidden;
    }

    .data-table table {
        width: 100%;
        border-collapse: collapse;
    }

    .data-table th {
        background: #f8f9fa;
        padding: 12px 15px;
        text-align: left;
        font-weight: 600;
        color: #2c3e50;
        border-bottom: 2px solid #eee;
    }

    .data-table td {
        padding: 12px 15px;
        border-bottom: 1px solid #eee;
        vertical-align: middle;
    }

    .data-table tr:hover {
        background: #f8f9fa;
    }

    .badge {
        padding: 5px 10px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 500;
    }

    .badge-success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .badge-danger {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .btn-icon {
        padding: 6px;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin: 0 2px;
        transition: all 0.3s;
    }

    .btn-icon:hover {
        background: rgba(0,0,0,0.05);
    }

    .text-danger { color: #dc3545; }

    .text-center {
        text-align: center;
    }

    .pagination {
        display: flex;
        justify-content: center;
        margin-top: 20px;
        gap: 5px;
    }

    .pagination a,
    .pagination span {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        color: #333;
        text-decoration: none;
        transition: all 0.3s;
    }

    .pagination a:hover {
        background: #f8f9fa;
        border-color: #3498db;
    }

    .pagination .current {
        background: #3498db;
        color: #fff;
        border-color: #3498db;
    }
    </style>

    <script>
    function toggleStatus(id) {
        if (confirm('确定要切换此排班的状态吗？')) {
            window.location.href = `private_courses.php?action=toggle&id=${id}`;
        }
    }

    function deleteSchedule(id) {
        if (confirm('确定要删除此排班吗？')) {
            window.location.href = `private_courses.php?action=delete&id=${id}`;
        }
    }
    </script>
</body>
</html>